/**
 * @FileName: TariffClassController.java
 * @Author
 * @Description:
 * @Date 2016年9月19日 下午2:09:12
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.admin;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.model.Activity;
import cn.hpclub.server.service.ActivityTariffClassRelationService;
import cn.hpclub.server.service.TariffService;
import com.jfinal.plugin.activerecord.Record;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.TariffClass;
import cn.hpclub.server.service.TariffClassService;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.validator.admin.TariffClassValidator;

public class TariffClassController extends BaseAdminController<TariffClass>{

    private static final String ORG_ID     = "org_id";
    private static Logger       logger     = LoggerFactory.getLogger(VnetReportController.class);
    private static final String IS_CHECKED = "isChecked";

    public void list(){
        int defaultOrgId = initOrgTree();
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        // 第一次进入，没有选中，则默认最高一层选中进行搜索。
        if(searchInfo.get(ORG_ID) == null){
            searchInfo.put(ORG_ID, String.valueOf(defaultOrgId));
        }

        List<Map.Entry<String, String>> activityList = TariffClassService.service.getActivityList();
        setAttr("activityList", activityList);
        String activity_selected = getAttr("activity_selected");
        if(StrKit.isBlank(activity_selected)){
            setAttr("activity_selected", -1);
        }
        String enabled_selected = getAttr("enabled_selected");
        if(StrKit.isBlank(enabled_selected)){
            setAttr("enabled_selected", -1);
        }



        logger.debug("TariffClassController.list");
        findByPageBySearchInfo(searchInfo);
        setAttrs(searchInfo);
        render("/admin/tariff_class_list.tpl");
    }

    private void findByPageBySearchInfo(ConcurrentHashMap<String, String> searchInfo){

        String select = "select u.user_name,j.DisplayName org_name," +
                "group_concat(DISTINCT ( concat(sv.name,'-',a.name) ))AS activity_name," +
                "t.* ";
        String sqlExceptSelect = TariffClassService.service.getSqlExceptSelect(searchInfo);
        int pageNumber = getParaToInt(PAGE_NUMBER, 1);
        int pageSize = getParaToInt(PAGE_SIZE, 10);
        Page<TariffClass> pager = TariffClass.dao.paginate(pageNumber, pageSize, select, sqlExceptSelect);
        /* 删除最后一页所有数据后，显示最后一页前一页 */
        if(pager.getPageNumber() > 1 && pager.getList().size() == 0){
            pager = TariffClass.dao.paginate(pageNumber - 1, getParaToInt("pageSize", 10), select, sqlExceptSelect);
        }

        setAttr("pager", pager);
    }

    @Before(Tx.class)
    public void delete(){
        boolean result = false;
        result = softlyDelById(Constant.Table.TARIFF_CLASS);
        delRelation();
        if(result){
            ajaxJsonSuccessMessage("删除成功");
        } else{
            ajaxJsonErrorMessage("删除失败");
        }

        // boolean result = false;
        // try{
        // delData();
        // result = true;
        // }
        // catch(Exception e){
        // e.printStackTrace();
        // }
        // finally{
        // if(result){
        // ajaxJsonSuccessMessage("删除成功");
        // } else{
        // ajaxJsonErrorMessage("删除失败");
        // }
        //
        // }
    }

    // @Before(Tx.class)
    // private void delData() throws Exception{
    // softlyDelById(Constant.Table.TARIFF_CLASS);
    // delRelation();
    // // throw new Exception();
    // }

    public boolean softlyDelById(String tableName){
        String[] ids = getParaValues("ids");

        StringBuffer sb = new StringBuffer();
        sb.append("update " + tableName + " set is_deleted = 1" + " where id in(");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }

            }
            sb.append(")");
        } else{
            return false;
        }
        ActivityTariffClassRelationService.service.deleteRelationByTariffClassIds(Arrays.asList(ids));
        return Db.update(sb.toString(), (Object[])ids) > 0;
    }

    private boolean delRelation(){

        String[] ids = getParaValues("ids");

        StringBuffer sb = new StringBuffer();
        sb.append("delete from " + Constant.Table.TARIFF_CLASS_RELATION + " where tariff_class_id in(");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            return false;
        }
        return Db.update(sb.toString(), (Object[])ids) > 0;
    }

    /*
     * 编辑
     */
    public void edit(){
        String id = getPara("id", "");
        List<Record> selected = new ArrayList<>();
        if(StrKit.notBlank(id)){
            TariffClass tariff = TariffClass.dao.findById(id);
            setAttr("tariffClass", tariff);
            selected = Db.find(
            " SELECT a.type,scv.name as detail_name,a.id,a.name,ar.activity_id,ar.tariff_class_id FROM activity_tariff_class_relation ar LEFT JOIN activity a ON ar.activity_id = a.id  "
                    + " LEFT JOIN sys_code_value scv ON a.type=scv.`value` LEFT JOIN sys_code_type sct ON scv.type_id = sct.id  WHERE ar.tariff_class_id =?  AND sct.`code`='HDLX' AND a.is_deleted=0 ",
            id);

            String activitySql = "SELECT a.id,a.name,a.type,sv.name as detail_name FROM activity a left join sys_code_value sv on a.type=sv.`value` LEFT JOIN sys_code_type sct ON sv.type_id=sct.id  where a.is_deleted=0  and sct.`code`='HDLX' ";
            List<Record> list = Db.find(activitySql);
            for(Record record : selected){
                String name = record.getStr("name");
                if(name.length() > 50){
                    record.set("name", name.substring(0, 47) + "...");
                }
                int activity_id = record.getInt("activity_id");
                for(Record records : list){
                    long p_id = records.getLong("id");
                    if(p_id == activity_id){
                        list.remove(records);
                        break;
                    }
                }
            }
            for(Record record : list){
                String tariffClassName = record.getStr("name");
                if(tariffClassName.length() > 50){
                    record.set("name", tariffClassName.substring(0, 47) + "...");
                }
            }
            setAttr("activityList", list);
            setAttr("activityTariffClassRelationList", selected);

        }
        render("/admin/tariff_class_add.tpl");
    }

    private TariffClass modalBind(boolean isAdd){
        TariffClass modal = new TariffClass();
        Integer id = getParaToInt("tariffClass.id", null);
        String name = getPara("tariffClass.name", "");// 业务名称
        boolean enabled = getParaToBoolean("tariffClass.enabled", false);
        String icon_url = getPara("tariffClass.icon_url", "");// 图标路径
        int sort = getParaToInt("sort",5);
        modal.set("id", id).set("name", name).set("enabled", enabled).set(TariffClass.ICON_URL, icon_url);
        modal.set("sort", sort);
        Date now = new Date();
        if(isAdd){
            int org_id = InterfaceUtil.getOrgId();// 当前用户机构id
            int creator = InterfaceUtil.getAdminId();// 当前用户id
            modal.set("created_time", now).set("org_id", org_id).set("created_by", creator).set("last_updated_time",
                    now);
        } else{
            modal.set("last_updated_time", now);
        }
        return modal;
    }

    /*
     * 新增
     */
    @Before({ Tx.class})
    public void save(){
        TariffClass modal = modalBind(true);
        modal.save();


        String activity_ids = getPara("activity_ids", null);
        List<Integer> activityIdList = new ArrayList<>();
        if(activity_ids.contains(",")){
            String[] activityIdArr = activity_ids.split(",");
            for(String activityId : activityIdArr){
                activityIdList.add(Integer.parseInt(activityId));
            }
        } else{
            activityIdList.add(Integer.parseInt(activity_ids));
        }
        ActivityTariffClassRelationService.service.saveRelation(modal.getInt(TariffClass.ID), activityIdList);


        redirect("/tariffClass/list");
    }

    public void add(){
        setAttr("tariffClass", new TariffClass());
        // setAttr(IS_CHECKED, 0);
        String activitySql = "SELECT a.id,a.name,a.type,sv.name as detail_name FROM activity a left join sys_code_value sv on a.type=sv.`value` LEFT JOIN sys_code_type sct ON sv.type_id=sct.id  where a.is_deleted=0  and sct.`code`='HDLX' ";
        List<Record> list = Db.find(activitySql);
        for(Record record : list){
            String name = record.getStr("name");
            if(name.length() > 50){
                record.set("name", name.substring(0, 47) + "...");
            }
        }
        List<Record> selected = new ArrayList<>();
        setAttr("activityList", list);
        setAttr("activityTariffClassRelationList", selected);
        render("/admin/tariff_class_add.tpl");
    }

    /*
     * 修改
     */
    @Before({ Tx.class })
    public void update(){
        TariffClass modal = modalBind(false);
        modal.update();
        ActivityTariffClassRelationService.service.deleteRelationByTariffClassId(modal.getInt(TariffClass.ID));

        String activity_ids = getPara("activity_ids", null);
        List<Integer> activityIdList = new ArrayList<>();
        if(activity_ids.contains(",")){
            String[] activityIdArr = activity_ids.split(",");
            for(String activityId : activityIdArr){
                activityIdList.add(Integer.parseInt(activityId));
            }
        } else{
            activityIdList.add(Integer.parseInt(activity_ids));
        }
        ActivityTariffClassRelationService.service.saveRelation(modal.getInt(TariffClass.ID), activityIdList);




        redirect("/tariffClass/list");
    }





    public void enable(){
        enableTariffClass(1, "启用");
    }

    public void disable(){
        enableTariffClass(0, "禁用");
    }

    private void enableTariffClass(int enabled, String actionName){
        String[] ids = getParaValues("ids");

        StringBuffer sb = new StringBuffer();
        sb.append("UPDATE tariff_class SET enabled = " + enabled + " WHERE id IN (");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            ajaxJsonErrorMessage(actionName + "失败");
            return;
        }
        boolean success = Db.update(sb.toString(), (Object[])ids) > 0;
        if(success){
            ajaxJsonSuccessMessage(actionName + "成功");
        } else{
            ajaxJsonErrorMessage(actionName + "失败");
        }
    }



    public void validityCodeUnique(){
        JSONObject jo = null;
        String tariffClassName = getPara("tariffClassName", "");
        int tariffClassId = getParaToInt("tariffClassId", 0);
        int org_id = InterfaceUtil.getOrgId();
        int city_org_id = getCityCode(org_id);
        boolean flag = TariffClassService.service.getTariffByCityAndCode(city_org_id, tariffClassName, tariffClassId);
        if(!flag){
            jo = setResponseObj(ClientApiConstant.ResultCode.SUCCESS_CODE, "大类名称唯一可用", null);
        } else{
            jo = setResponseObj(ClientApiConstant.ResultCode.FAILED, "大类名称在当前地市已存在", null);
        }
        renderJson(jo.toString());
    }
    private int getCityCode(int orgId){
        if(orgId == InterfaceUtil.ID_TOP){
            return orgId;
        } else{
            Record record = Db.findFirst("SELECT CityCode FROM organization WHERE id=?", orgId);
            return record.getInt("CityCode");
        }
    }


}
